package com.chaosj.memory.handlers;

import com.chaosj.memory.IToolHandler;
import com.chaosj.memory.dto.PokerDto;
import com.google.common.base.Splitter;

import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * @className: PokerHandler
 * @description:
 * @author: caoyangjie
 * @date: 2021/8/10
 **/
public class PokerHandler extends AbstractToolHandler<PokerDto> {

    @Override
    public String name() {
        return "poker";
    }

    @Override
    public void round(StringBuffer stringBuffer, boolean isBefore) {
        if( isBefore ){
            stringBuffer.append("*********************************************** 随机扑克生成器 start ***********************************************\n");
        }else{
            stringBuffer.append("*********************************************** 随机扑克生成器 end *************************************************\n");
        }
    }

    @Override
    public void handler(PokerDto req, StringBuffer outBuffer) {
        Set<String> pokerSet = new HashSet<>();
        Set<Integer> pokerPool = new HashSet<>();
        List<String> colors = Splitter.on(",").splitToList("黑桃 ,红桃 ,梅花 ,方块 ,小王 ,大王 ");
        int randNumber = 0;
        String color = null;
        for ( int i = 0; i < req.getSize(); i ++ ){
            do{
                randNumber = next.nextInt(req.getSize()+1);
            } while ( pokerPool.contains(randNumber) || randNumber == 0 );
            pokerPool.add(randNumber);
            String colorPoker = num2Poker(randNumber, colors);
            pokerSet.add(colorPoker);
            outBuffer.append("|"+colorPoker);
            if( pokerSet.size() % 10 == 0 ){
                outBuffer.append("|\n");
            }
        }
        outBuffer.append("|\n");
    }

    private String num2Poker(int num, List<String> colors){

        String poker = "";
        int colorIndex = (num - 1) / 13;
        int number = (num-1) % 13;
        if( colorIndex == 4 ){
            return colors.get(colorIndex+number)+String.format("[%s]  ",num);
        }
        switch (number){
            case 9:
                poker = "0";
                break;
            case 10:
                poker = "J";
                break;
            case 11:
                poker = "Q";
                break;
            case 12:
                poker = "K";
                break;
            default:
                poker = (number+1)+"";
                break;
        }
        return colors.get(colorIndex)+poker+String.format(" [%s]",num<10?"0"+num:num);
    }

    @Override
    public PokerDto cmd2Dto(String[] args) {
        String size = args.length>1? args[1]:"54";
        return new PokerDto().setSize(Integer.valueOf(size));
    }
}
